import NProgress from 'nprogress'; // progress bar
import usePermission from '@/hooks/permission';
import { useUserStore, useAppStore, useRouterStore } from '@/store';
import { NOT_FOUND_ROUTE } from '@/router/routes/base';
import { isLogin, getToken } from '@/utils/auth';
import router from '@/router';
import { Message } from '@arco-design/web-vue';

const whiteList = ['/login', '/register'];
const modules = import.meta.glob('@/views/client-side/**/*');

export const beforeEachs = async (to: any, from: any, next: any) => {
  NProgress.start();
  const Permission = usePermission();
  const permissionsAllow = Permission.accessRouter(to);
  let routerStore;
  if (whiteList.includes(to.path)) return next();
  if (!routerStore) routerStore = useRouterStore();
  if (sessionStorage.getItem('loginInfo')) {
    if (router.hasRoute(to.path.split('/').pop())) {
      return next();
    } else {
      try {
        const check: any = await routerStore.generateRoutes();
        let currenRoutes: any = router.options.routes;
        check.forEach((item: any) => {
          currenRoutes.push(item);
        });
        if (currenRoutes[currenRoutes.length - 1].path !== '/:pathMatch(.*)*') {
          currenRoutes.push(NOT_FOUND_ROUTE);
        }
        currenRoutes.forEach((item: any) => {
          router.addRoute({
            name: item.name,
            path: item.path,
            component: item.component,
            meta: item.meta,
            children: item.children,
          });
        });
        return next({ ...to, replace: true });
      } catch (err: unknown) {
        console.log(err);
        Message.warning('登录失败,请重新登录');
        return next('/login');
      }
    }
  } else {
    Message.warning('未登录,无法访问');
    return next('/login');
  }
};

export const afterEach = () => {
  NProgress.done();
};
